
export const sendRequest = async (channel: string, data: any) => {
  var ret = await (window as any).electron.sendRequest(channel, data);
  console.log(channel, data, ret);
  return ret;
};

//定义将Date对象转换为字符串函数
export function timeToString(timeObj: Date) {
  const year = timeObj.getFullYear();
  const month = timeObj.getMonth();
  const date = timeObj.getDate();
  const time = timeObj.toTimeString().split(" ")[0];
  const rex = new RegExp(/:/g);
  return year + "-" + month + "-" + date + " " + time.replace(rex, ":");
}

// 根据字节计算文件大小
export function convertBytesToReadableSize(bytes: number): string {
  const units = ["B", "KB", "MB", "GB", "TB"];
  let unitIndex = 0;
  let size = bytes;

  // 找到合适的单位
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }

  // 保留两位小数
  return `${size.toFixed(2)} ${units[unitIndex]}`;
}

// 计算字符串的哈希值
export function hashString(str: string) {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  return hash;
}

export const delay = (timeout: number) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(null);
    }, timeout);
  });
};

export const asyncForEach = async (array: any[], fromIndex: number, toIndex: number, func: (item: any, index: number) => Promise<void>) => {
  if (fromIndex > toIndex) {
    var from = array.length - 1;
    if (fromIndex >= 0) {
      from = fromIndex;
    }
    var to = 0;
    if (toIndex >= 0) {
      to = toIndex;
    }
    // if(from && to){
    //   console.log("asyncForEach");
    // }
    for (let i = from; i >= to; i--) {
      await func(array[i], i);
    }
  } else {
    var from = 0;
    if (fromIndex >= 0) {
      from = fromIndex;
    }
    var to = array.length - 1;
    if (toIndex >= 0) {
      to = toIndex;
    }
    for (let i = from; i <= to; i++) {
      await func(array[i], i);
    }
  }
}
